package com.rainbowno6.combatcalculator


import android.content.Context
import android.os.VibrationEffect
import android.os.Vibrator

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext

import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import java.io.*
import androidx.compose.foundation.clickable
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.AlertDialog
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue


import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Visibility

import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import java.io.File


import androidx.compose.foundation.gestures.detectTapGestures



import androidx.navigation.compose.rememberNavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.activity.compose.BackHandler

import androidx.navigation.NavType
import androidx.navigation.navArgument

import net.objecthunter.exp4j.ExpressionBuilder

import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll


import androidx.compose.ui.text.TextRange
import androidx.compose.foundation.Image
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource

import com.google.accompanist.flowlayout.FlowRow



import androidx.compose.foundation.background
import androidx.compose.foundation.shape.RoundedCornerShape

import androidx.compose.foundation.border

import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign

import androidx.compose.animation.*
import androidx.compose.animation.core.*

import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.filled.LightMode
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme

import androidx.compose.material.icons.filled.Edit


import androidx.compose.material.icons.filled.Backspace

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically

import androidx.compose.material.icons.filled.Close

import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExposedDropdownMenuBox

import kotlin.math.abs

import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

import androidx.compose.ui.platform.LocalFocusManager

import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.text.SpanStyle


import androidx.compose.foundation.shape.CircleShape

import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

import kotlinx.coroutines.delay

import androidx.compose.material3.Checkbox
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.CheckBoxOutlineBlank


import androidx.compose.ui.input.pointer.pointerInput

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

import android.os.Environment
import android.media.MediaScannerConnection
import android.util.Log
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import android.os.Build
import android.content.Intent
import androidx.core.content.FileProvider
import java.util.*
import androidx.core.content.ContextCompat
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import android.provider.Settings

import kotlin.math.max


import kotlinx.coroutines.CoroutineScope



object VibrationUtils {
    fun vibrate(context: Context, duration: Long = 200) {
        val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        if (vibrator.hasVibrator()) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
            } else {
                @Suppress("DEPRECATION")
                vibrator.vibrate(duration)
            }
        }
    }
}

@Serializable
data class FormulaData(
    val name: String,
    val expression: String,
    val variables: List<Variable>,
    val targetVariable: String = ""
)

@Serializable
data class Variable(
    val name: String,
    val defaultValue: String
)

object FileManager {
    private const val EXPORT_FILE_NAME = "CombatCalculator_Formulas.json"
    private const val EXPORT_FOLDER_NAME = "CombatCalculatorExports"
    private const val STORAGE_PERMISSION_CODE = 1001

    @Composable
    fun ExportOptionsDialog(
        formulas: List<Pair<String, Long>>,
        onDismiss: () -> Unit,
        onExport: (List<String>) -> Unit
    ) {
        val context = LocalContext.current
        var showSuccessDialog by remember { mutableStateOf(false) }
        var exportedFileInfo by remember { mutableStateOf<Pair<String, String>?>(null) }
        var selectedFormulas by remember { mutableStateOf(setOf<String>()) }
        val selectedCount = selectedFormulas.size



        AlertDialog(
            onDismissRequest = onDismiss,
            title = {
                Column {
                    Text("选择要导出的公式")
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "已选择: $selectedCount/${formulas.size}",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            },
            text = {
                Column {
                    // 全选/取消全选按钮
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                selectedFormulas = if (selectedCount == formulas.size) {
                                    emptySet()
                                } else {
                                    formulas.map { it.first }.toSet()
                                }
                            }
                            .padding(vertical = 8.dp)
                    ) {
                        Checkbox(
                            checked = selectedCount == formulas.size,
                            onCheckedChange = {
                                selectedFormulas = if (it) {
                                    formulas.map { it.first }.toSet()
                                } else {
                                    emptySet()
                                }
                            }
                        )
                        Text(
                            text = if (selectedCount == formulas.size) "取消全选" else "全选",
                            modifier = Modifier.padding(start = 8.dp)
                        )
                    }

                    Divider()

                    // 公式列表
                    LazyColumn(modifier = Modifier.heightIn(max = 400.dp)) {
                        items(formulas) { (name, _) ->
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        selectedFormulas = if (selectedFormulas.contains(name)) {
                                            selectedFormulas - name
                                        } else {
                                            selectedFormulas + name
                                        }
                                    }
                                    .padding(vertical = 8.dp)
                            ) {
                                Checkbox(
                                    checked = selectedFormulas.contains(name),
                                    onCheckedChange = { checked ->
                                        selectedFormulas = if (checked) {
                                            selectedFormulas + name
                                        } else {
                                            selectedFormulas - name
                                        }
                                    }
                                )
                                Text(
                                    text = name,
                                    modifier = Modifier.padding(start = 8.dp)
                                )
                            }
                        }
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        if (selectedFormulas.isNotEmpty()) {
                            val selectedFormulasData = FileManager.getSelectedFormulas(context, selectedFormulas.toList())
                            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                                .format(Date())
                            val fileName = "战斗计算器导出_共${selectedFormulas.size}个公式_$timeStamp.json"

                            val exportedFile = FileManager.exportFormulas(context, selectedFormulasData, fileName)

                            exportedFile?.let {
                                exportedFileInfo = fileName to FileManager.getExportDirPath(context)
                                showSuccessDialog = true
                                onExport(selectedFormulas.toList())
                            } ?: run {
                                Toast.makeText(context, "导出失败", Toast.LENGTH_SHORT).show()
                            }
                        }
                    },
                    enabled = selectedFormulas.isNotEmpty()
                ) {
                    Text("导出($selectedCount)")
                }
            },
            dismissButton = {
                Button(onClick = onDismiss) {
                    Text("取消")
                }
            }
        )
    }

    // Android 10+ 兼容方案
    private fun getExportDir(context: Context): File {
        val appName = "战斗计算器导出文件" // 使用固定应用名称
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 使用下载目录下的应用专属文件夹
            File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                appName
            ).apply { mkdirs() }
        } else {
            // 旧版本使用文档目录下的应用专属文件夹
            File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
                appName
            ).apply { mkdirs() }
        }
    }

    // 检查存储权限
    fun checkStoragePermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        }
    }

    // 请求权限
    fun requestStoragePermission(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
            activity.startActivity(intent)
        } else {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                STORAGE_PERMISSION_CODE
            )
        }
    }

    fun getExportDirPath(context: Context): String {
        return getExportDir(context).absolutePath
    }

    fun exportToDocuments(context: Context, data: String, fileName: String): File? {
        return try {
            val exportDir = getExportDir(context)
            val exportFile = File(exportDir, fileName)

            exportFile.writeText(data)

            // 刷新媒体库使文件立即可见
            MediaScannerConnection.scanFile(
                context,
                arrayOf(exportFile.absolutePath),
                null,
                null
            )

            exportFile
        } catch (e: Exception) {
            Log.e("FileExport", "导出失败", e)
            null
        }
    }

    @Composable
    fun ExportButton(
        onExportSuccess: (File) -> Unit = {},
        onExportFailure: () -> Unit = {},
        modifier: Modifier = Modifier,
        enabled: Boolean = true
    ) {
        val context = LocalContext.current
        var showSuccessDialog by remember { mutableStateOf(false) }
        var exportedFileInfo by remember { mutableStateOf<Pair<String, String>?>(null) }



        Button(
            onClick = {
                val allFormulas = loadAllFormulas(context)
                val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                    .format(Date())
                val fileName = "全部公式_$timeStamp.json"

                val exportedFile = FileManager.exportFormulas(context, allFormulas, fileName)

                exportedFile?.let {
                    // 保存文件信息用于对话框显示
                    exportedFileInfo = fileName to FileManager.getExportDirPath(context)
                    showSuccessDialog = true
                    onExportSuccess(it)
                } ?: run {
                    Toast.makeText(
                        context,
                        "导出失败，请检查权限",
                        Toast.LENGTH_SHORT
                    ).show()
                    onExportFailure()
                }
            },
            modifier = modifier,
            enabled = enabled
        ) {
            Text("全部导出")
        }
    }



    private fun shareFile(context: Context, file: File) {
        val shareIntent = Intent(Intent.ACTION_SEND).apply {
            type = "application/json"
            putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(
                context,
                "${context.packageName}.provider",
                file
            ))
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        context.startActivity(Intent.createChooser(shareIntent, "分享公式文件"))
    }

    // 修改导出方法，支持传入特定公式列表
    fun exportFormulas(
        context: Context,
        formulas: List<FormulaData>,
        fileName: String = "",
        persistToStorage: Boolean = true // 新增参数
    ): File? {
        return try {
            val exportDir = getExportDir(context)
            val finalFileName = if (fileName.isBlank()) {
                val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                    .format(Date())
                "战斗公式_$timeStamp.json"
            } else {
                fileName
            }

            val exportFile = File(exportDir, finalFileName)

            if (persistToStorage) { // 只有需要持久化时才实际写入
                exportFile.writeText(Json { prettyPrint = true }.encodeToString(formulas))
                MediaScannerConnection.scanFile(context, arrayOf(exportFile.absolutePath), null, null)
            }

            exportFile // 无论如何都返回File对象
        } catch (e: Exception) {
            Log.e("Export", "导出失败", e)
            null
        }
    }

    // 新增方法：获取选中的公式数据
    fun getSelectedFormulas(context: Context, selectedNames: List<String>): List<FormulaData> {
        return selectedNames.mapNotNull { name ->
            loadFormulaData(context, name)
        }
    }

    // 从外部文件导入公式
    fun importFormulas(context: Context, fileUri: Uri): List<FormulaData>? {
        return try {
            context.contentResolver.openInputStream(fileUri)?.use { inputStream ->
                val jsonString = inputStream.bufferedReader().readText()
                Json.decodeFromString<List<FormulaData>>(jsonString)
            }
        } catch (e: Exception) {
            Log.e("FileManager", "导入失败", e)
            null
        }
    }
}

private val DarkColorScheme = darkColorScheme(
    primary = Color(0xFFBB86FC),
    secondary = Color(0xFF03DAC6),
    tertiary = Color(0xFF3700B3),
    background = Color(0xFF121212),  // 确保这是暗色
    surface = Color(0xFF1E1E1E),    // 卡片等表面颜色
    onPrimary = Color.Black,
    onSecondary = Color.Black,
    onBackground = Color(0xFFFFFFFF), // 背景上的文字颜色
    onSurface = Color(0xFFFFFFFF),    // 表面上的文字颜色
    error = Color(0xFFCF6679)
)

private val LightColorScheme = lightColorScheme(
    primary = Color(0xFF6200EE),
    secondary = Color(0xFF03DAC6),
    tertiary = Color(0xFF3700B3),
    background = Color.White,
    surface = Color.White,
    onPrimary = Color.White,
    onSecondary = Color.Black,
    onBackground = Color.Black,
    onSurface = Color.Black,
    error = Color(0xFFB00020)
)

/**
 * 主Activity类
 *
 * 负责以下核心功能：
 * - 应用程序初始化和生命周期管理
 * - 主题设置管理（日间/夜间模式切换）
 * - 首次运行时的示例公式添加
 * - 状态保存和恢复
 * - 用户界面的主要布局和导航
 */
class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val prefs = getPreferences(Context.MODE_PRIVATE)
        val defaultDarkMode = prefs.getBoolean("dark_theme", false)

        // 检查是否是第一次运行，如果是则添加示例公式
        val isFirstRun = prefs.getBoolean("first_run", true)
        if (isFirstRun) {
            addSampleFormulas(this)
            prefs.edit().putBoolean("first_run", false).apply()
        }

        setContent {
            var isDarkTheme by remember { mutableStateOf(defaultDarkMode) }

            LaunchedEffect(isDarkTheme) {
                prefs.edit().putBoolean("dark_theme", isDarkTheme).apply()
            }

            // 使用Crossfade实现平滑过渡
            Crossfade(
                targetState = isDarkTheme,
                animationSpec = tween(1000) // 1000毫秒的过渡时间
            ) { darkMode ->
                MaterialTheme(
                    colorScheme = if (darkMode) DarkColorScheme else LightColorScheme
                ) {
                    Surface(
                        modifier = Modifier.fillMaxSize(),
                        color = MaterialTheme.colorScheme.background
                    ) {
                        CombatCalculatorApp(
                            onThemeChange = { isDarkTheme = !isDarkTheme },
                            isDarkTheme = darkMode
                        )
                    }
                }
            }
        }
    }

    private fun addSampleFormulas(context: Context) {
        // 示例公式1: 牛顿第二定律
        saveFormula(
            context = context,
            name = "牛顿第二定律（示例）",
            content = "F = m * a",
            variables = listOf("F" to "1", "m" to "1", "a" to "1"),
            target = "F"
        )

        // 示例公式2: 动能公式
        saveFormula(
            context = context,
            name = "动能公式（示例）",
            content = "E = 0.5 * m * v^2",
            variables = listOf("E" to "1", "m" to "1", "v" to "1"),
            target = "E"
        )

        // 示例公式3: 欧姆定律
        saveFormula(
            context = context,
            name = "欧姆定律（示例）",
            content = "U = I * R",
            variables = listOf("U" to "1", "I" to "1", "R" to "1"),
            target = "U"
        )
    }

    // 修改saveFormula函数以支持直接传入变量列表
    private fun saveFormula(
        context: Context,
        name: String,
        content: String,
        variables: List<Pair<String, String>>,
        target: String = ""
    ) {
        try {
            val formulaData = buildString {
                append("[formula]\n")
                append("name=$name\n")
                append("expression=$content\n")
                if (target.isNotBlank()) {
                    append("target=$target\n")
                }
                append("[variables]\n")
                variables.forEach { (varName, defaultValue) ->
                    append("$varName=$defaultValue\n")
                }
            }

            val fileName = "formula_${name.trim()}.txt"
            context.openFileOutput(fileName, Context.MODE_PRIVATE).use {
                it.write(formulaData.toByteArray())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onBackPressed() {
        // 保留默认返回行为
        super.onBackPressed()
    }
}

/**
 * 应用主界面组件
 * 负责管理导航状态和屏幕切换，是整个应用的核心UI组件
 * @param onThemeChange 主题切换回调函数
 * @param isDarkTheme 当前是否为暗色主题
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CombatCalculatorApp(
    onThemeChange: () -> Unit,
    isDarkTheme: Boolean
) {
    val navController = rememberNavController()
    val context = LocalContext.current
    var selectedFormula by remember { mutableStateOf<String?>(null) }


    MaterialTheme {
        Scaffold { paddingValues ->
            NavHost(
                modifier = Modifier.padding(paddingValues),
                navController = navController,
                startDestination = Screen.MAIN_MENU.name,
                enterTransition = { fadeIn(animationSpec = tween(150)) },
                exitTransition = { fadeOut(animationSpec = tween(150)) }
            ) {
                composable(Screen.MAIN_MENU.name) {
                    MainMenuScreen(
                        onFormulaEditorClick = { navController.navigate(Screen.FORMULA_EDITOR.name) },
                        onViewFormulasClick = { navController.navigate(Screen.VIEW_FORMULAS.name) },
                        onExitClick = { (context as? ComponentActivity)?.finish() },
                        onThemeChange = onThemeChange,
                        isDarkTheme = isDarkTheme
                    )
                }

                composable(Screen.FORMULA_EDITOR.name) {
                    FormulaEditorScreen(
                        onBackClick = { navController.popBackStack() }
                    )
                }

                composable(Screen.VIEW_FORMULAS.name) {
                    ViewFormulasScreen(
                        onBackClick = { navController.popBackStack() },
                        onFormulaClick = { name ->
                            navController.navigate("${Screen.FORMULA_CALCULATE.name}/$name")
                        },
                        onDeleteClick = { name ->
                            // 这里不再需要处理导航逻辑
                        },

                    )
                }

                composable(
                    route = "${Screen.FORMULA_CALCULATE.name}/{formulaName}",
                    arguments = listOf(navArgument("formulaName") { type = NavType.StringType })
                ) { backStackEntry ->
                    FormulaCalculateScreen(
                        formulaName = backStackEntry.arguments?.getString("formulaName") ?: "",
                        onBackClick = { navController.popBackStack() }
                    )
                }
            }
        }
    }
}

/**
 * 屏幕状态枚举
 */
enum class Screen {
    MAIN_MENU,
    FORMULA_EDITOR,
    VIEW_FORMULAS,
    FORMULA_CALCULATE
}

/**
 * 主菜单界面组件
 * 显示应用的主要功能入口，包括：
 * - 公式编辑器入口
 * - 公式查看/删除入口
 * - 主题切换功能
 * - 退出应用选项
 *
 * @param onFormulaEditorClick 点击公式编辑器按钮的回调函数
 * @param onViewFormulasClick 点击查看公式按钮的回调函数
 * @param onExitClick 点击退出按钮的回调函数
 * @param onThemeChange 主题切换回调函数
 * @param isDarkTheme 当前是否为暗色主题
 */
@Composable
fun MainMenuScreen(
    onFormulaEditorClick: () -> Unit,
    onViewFormulasClick: () -> Unit,
    onExitClick: () -> Unit,
    onThemeChange: () -> Unit,
    isDarkTheme: Boolean
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Surface(
            modifier = Modifier.fillMaxSize(),
            color = MaterialTheme.colorScheme.background
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(vertical = 24.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top  // 修改为顶部对齐
            ) {
                // 标题部分保持不变
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "CombatCalculator",
                        style = MaterialTheme.typography.displaySmall.copy(
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.primary
                        ),
                        modifier = Modifier.padding(bottom = 4.dp)
                    )
                    Text(
                        text = "战斗计算器",
                        style = MaterialTheme.typography.headlineMedium.copy(
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.secondary
                        )
                    )
                }

                Spacer(modifier = Modifier.height(16.dp))  // 减少标题和图片之间的间距

                // 图片部分保持不变
                Image(
                    painter = painterResource(id = R.drawable.combatcalculator),
                    contentDescription = "战斗计算器图标",
                    modifier = Modifier
                        .size(150.dp)
                        .padding(8.dp),
                    contentScale = ContentScale.Fit
                )

                Spacer(modifier = Modifier.height(8.dp))  // 减少图片和按钮之间的间距

                // 按钮部分 - 移除weight修饰符
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.padding(top = 8.dp)  // 添加顶部内边距
                ) {
                    // 夜间模式切换按钮
                    Button(
                        onClick = onThemeChange,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 8.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        )
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                imageVector = if (isDarkTheme) Icons.Default.LightMode else Icons.Default.DarkMode,
                                contentDescription = "主题切换",
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(if (isDarkTheme) "切换至日间模式" else "切换至夜间模式")
                        }
                    }

                    // 公式编辑器按钮
                    Button(
                        onClick = onFormulaEditorClick,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 8.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        )
                    ) {
                        Text("公式编辑器")
                    }

                    // 查看/删除公式按钮
                    Button(
                        onClick = onViewFormulasClick,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 8.dp),
                        colors = ButtonDefaults.buttonColors(  // 这里修正
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        )
                    ) {
                        Text("查看/删除公式")
                    }


                    // 退出程序按钮（红色）
                    Button(
                        onClick = onExitClick,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 8.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.error,
                            contentColor = MaterialTheme.colorScheme.onError
                        )
                    ) {
                        Text("退出程序")
                    }
                }

                // 底部版权信息 - 使用Spacer撑开剩余空间
                Spacer(modifier = Modifier.weight(1f))
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.padding(bottom = 16.dp)
                ) {
                    Text(
                        text = "Powered by Android & TencentCodeBuddy",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = "Created By 忍冬(Mr.R) 2025.05.18",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}




/**
 * 查看公式列表界面组件
 * 显示所有保存的公式，支持以下功能：
 * - 显示公式列表
 * - 左滑删除公式
 * - 点击查看公式详情
 * - 批量选择和删除
 * - 导入导出公式
 *
 * @param onBackClick 返回按钮点击回调函数
 * @param onFormulaClick 点击公式项的回调函数
 * @param onDeleteClick 删除公式的回调函数

 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ViewFormulasScreen(
    onBackClick: () -> Unit,
    onFormulaClick: (String) -> Unit,
    onDeleteClick: (String) -> Unit,

) {
    val context = LocalContext.current
    val formulas = remember { mutableStateListOf<Pair<String, Long>>() }
    var searchQuery by remember { mutableStateOf("") }
    val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) }
    var deletingFormula by remember { mutableStateOf<String?>(null) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var selectedFormulas by remember { mutableStateOf(setOf<String>()) }
    var showBulkDeleteDialog by remember { mutableStateOf(false) }
    var selectedUri by remember { mutableStateOf<Uri?>(null) }
    var showImportDialog by remember { mutableStateOf(false) }
    var showExportOptions by remember { mutableStateOf(false) }
    var exportedFileInfo by remember { mutableStateOf<Pair<String, String>?>(null) }

    var progressStartTime by remember { mutableStateOf(0L) }


    val filePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            selectedUri = it
            showImportDialog = true  // 只有选择了文件才显示导入确认
        }
    }

    // Export options dialog
    var showProgress by remember { mutableStateOf(false) }
    var progressText by remember { mutableStateOf("") }
    var showExportSuccessDialog by remember { mutableStateOf(false) }

    var isExporting by remember { mutableStateOf(false) }

    if (showExportOptions) {
        FileManager.ExportOptionsDialog(
            formulas = formulas,
            onDismiss = { if (!isExporting) showExportOptions = false },
            onExport = { selectedNames ->
                isExporting = true
                showProgress = true
                progressText = "请稍候..."

                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        val selectedFormulas = FileManager.getSelectedFormulas(context, selectedNames)
                        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault())
                            .format(Date())
                        val fileName = "战斗计算器导出_共${selectedFormulas.size}个公式_$timeStamp.json"

                        val exportedFile = FileManager.exportFormulas(
                            context,
                            selectedFormulas,
                            fileName,
                            persistToStorage = false // 不实际写入存储
                        )
                        delay(1000) // Ensure progress shows for at least 1 second

                        withContext(Dispatchers.Main) {
                            isExporting = false
                            showProgress = false
                            showExportOptions = false
                            if (exportedFile != null) {
                                exportedFileInfo = fileName to FileManager.getExportDirPath(context)
                                showExportSuccessDialog = true
                            } else {
                                Toast.makeText(context, "导出失败", Toast.LENGTH_SHORT).show()
                            }
                        }
                    } catch (e: Exception) {
                        withContext(Dispatchers.Main) {
                            isExporting = false
                            showProgress = false
                            Toast.makeText(context, "导出出错: ${e.message}", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
        )
    }



    // 进度条标志
            if (showProgress) {
                AlertDialog(
                    onDismissRequest = { /* 不允许取消 */ },
                    title = { Text("正在处理...") },
                    text = {
                        Column {
                            LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
                            Spacer(Modifier.height(8.dp))
                            Text(progressText)
                        }
                    },
                    confirmButton = {
                        Button(
                            onClick = { /* 无操作 */ },
                            enabled = false,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color.Gray,
                                contentColor = Color.LightGray
                            )
                        ) {
                            Text("确定")
                        }
                    }
                )
            }

    // 导出成功提示
    if (showExportSuccessDialog) {
        AlertDialog(
            onDismissRequest = { showExportSuccessDialog = false },
            title = { Text("导出成功") },
            text = {
                Column {
                    Text("公式已成功导出:")
                    Spacer(modifier = Modifier.height(8.dp))
                    Text("【文件名】: ${exportedFileInfo?.first ?: "未知"}")
                    Text("--------------------")
                    Spacer(modifier = Modifier.height(4.dp))
                    Text("【位置】: ${exportedFileInfo?.second ?: "未知"}")
                }
            },
            confirmButton = {
                Button(onClick = { showExportSuccessDialog = false }) {
                    Text("确定")
                }
            }
        )
    }

    // 导入确认提示
    if (showImportDialog && selectedUri != null) {
        AlertDialog(
            onDismissRequest = {
                showImportDialog = false
                selectedUri = null
            },
            title = { Text("导入公式") },
            text = { Text("确定要导入这些公式吗？可能会覆盖同名公式，建议先使用导出功能对已有公式备份后再导入新的公式！") },
            confirmButton = {
                Button(
                    onClick = {
                        showImportDialog = false
                        selectedUri?.let { uri ->
                            // 开始显示进度条
                            showProgress = true
                            progressStartTime = System.currentTimeMillis()

                            CoroutineScope(Dispatchers.IO).launch {
                                val importedFormulas = FileManager.importFormulas(context, uri)

                                // 计算剩余需要显示的时间
                                val elapsed = System.currentTimeMillis() - progressStartTime
                                val remaining = max(0, 1000 - elapsed)

                                delay(remaining) // 确保总共显示至少1秒

                                withContext(Dispatchers.Main) {
                                    showProgress = false

                                    if (importedFormulas != null) {
                                        // 重置选中状态
                                        selectedFormulas = emptySet()

                                        importedFormulas.forEach { formula ->
                                            saveImportedFormula(context, formula)
                                        }
                                        // 清空并重新加载公式列表
                                        formulas.clear()
                                        formulas.addAll(loadFormulasWithTimestamps(context))

                                        Toast.makeText(
                                            context,
                                            "成功导入 ${importedFormulas.size} 个公式",
                                            Toast.LENGTH_LONG
                                        ).show()
                                    } else {
                                        Toast.makeText(
                                            context,
                                            "导入失败，文件格式不正确",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                }
                            }
                        }
                        selectedUri = null
                    }
                ) {
                    Text("确认导入")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showImportDialog = false
                        selectedUri = null
                    }
                ) {
                    Text("取消")
                }
            }
        )
    }

    // 处理返回按键逻辑
    BackHandler(enabled = selectedFormulas.isNotEmpty()) {
        if (selectedFormulas.isNotEmpty()) {
            // 在批量选择模式下，点击返回键退出批量选择
            selectedFormulas = emptySet()
        } else {
            // 正常模式下返回上一页
            onBackClick()
        }
    }

    // 加载公式列表
    LaunchedEffect(Unit) {
        val formulaFiles = context.fileList()
            ?.filter { it.startsWith("formula_") && it.endsWith(".txt") }
            ?.map { fileName ->
                val name = fileName.removePrefix("formula_").removeSuffix(".txt")
                val file = File(context.filesDir, fileName)
                name to file.lastModified()
            } ?: emptyList()

        formulas.addAll(formulaFiles.sortedBy { it.second })
    }

    // 过滤公式列表
    val filteredFormulas = remember(formulas, searchQuery) {
        if (searchQuery.isEmpty()) {
            formulas
        } else {
            formulas.filter { (name, timestamp) ->
                name.contains(searchQuery, ignoreCase = true) ||
                        dateFormat.format(Date(timestamp)).contains(searchQuery)
            }
        }
    }

    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        // 在顶部添加进度条
        if (showProgress) {
            LinearProgressIndicator(
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))
        }

        // Top action bar
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            // Back button
            Button(
                onClick = {
                    if (selectedFormulas.isNotEmpty()) {
                        selectedFormulas = emptySet()
                    } else {
                        onBackClick()
                    }
                },
                modifier = Modifier.padding(bottom = 16.dp)
            ) {
                Text(if (selectedFormulas.isNotEmpty()) "退出选择" else "返回主菜单")
            }

            // Export/Import buttons
            Row {
                // Export button - now opens options dialog
                Button(
                    onClick = { showExportOptions = true },
                    modifier = Modifier.padding(end = 8.dp),
                    enabled = formulas.isNotEmpty() && !isExporting
                ) {
                    Text(if (isExporting) "导出中..." else "导出")
                }

                // Import button
                Button(
                    onClick = {
                        // 直接启动文件选择器，不显示任何提示
                        filePickerLauncher.launch("application/json")
                    }
                ) {
                    Text("导入")
                }
            }
        }



        // 搜索框
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            elevation = CardDefaults.cardElevation(4.dp)
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = "搜索公式",
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.primary
                )
                Spacer(modifier = Modifier.height(8.dp))
                TextField(
                    value = searchQuery,
                    onValueChange = { searchQuery = it },
                    label = { Text("输入公式名称或日期") },
                    modifier = Modifier.fillMaxWidth(),
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Edit,
                            contentDescription = "搜索"
                        )
                    },
                    singleLine = true,
                    colors = TextFieldDefaults.textFieldColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f)
                    )
                )
                Text(
                    text = "可以按公式名称或创建日期(yyyy-MM-dd)搜索",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline,
                    modifier = Modifier.padding(top = 4.dp)
                )
            }
        }

        // 公式列表
        if (filteredFormulas.isEmpty()) {
            if (formulas.isEmpty()) {
                Text(
                    "暂无保存的公式",
                    modifier = Modifier.fillMaxWidth().padding(16.dp),
                    textAlign = TextAlign.Center
                )
            } else {
                Text(
                    "未找到匹配的公式",
                    modifier = Modifier.fillMaxWidth().padding(16.dp),
                    textAlign = TextAlign.Center
                )
            }
        } else {
            // 批量选择操作栏
            if (selectedFormulas.isNotEmpty()) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "已选择 ${selectedFormulas.size} 项",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        // 添加"全选"提示文本
                        Text(
                            text = "全选",
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier.padding(end = 8.dp)
                        )
                        IconButton(
                            onClick = {
                                if (selectedFormulas.size == filteredFormulas.size) {
                                    selectedFormulas = emptySet()
                                } else {
                                    VibrationUtils.vibrate(context)
                                    selectedFormulas = filteredFormulas.map { it.first }.toSet()
                                }
                            }
                        ) {
                            Icon(
                                imageVector = if (selectedFormulas.size == filteredFormulas.size)
                                    Icons.Default.CheckBox
                                else
                                    Icons.Default.CheckBoxOutlineBlank,
                                contentDescription = "全选",
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                        IconButton(
                            onClick = {
                                VibrationUtils.vibrate(context)
                                showBulkDeleteDialog = true
                            }
                        ) {
                            Icon(
                                imageVector = Icons.Default.Delete,
                                contentDescription = "批量删除",
                                tint = MaterialTheme.colorScheme.error
                            )
                        }
                        IconButton(
                            onClick = {
                                VibrationUtils.vibrate(context)
                                selectedFormulas = emptySet()
                            }
                        ) {
                            Icon(
                                imageVector = Icons.Default.Close,
                                contentDescription = "取消选择"
                            )
                        }
                    }
                }
            }

            // 显示搜索结果数量
            Text(
                text = "找到 ${filteredFormulas.size} 个公式--长按可批量删除",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            LazyColumn {
                items(filteredFormulas) { (formulaName, lastModified) ->
                    val isSelected = selectedFormulas.contains(formulaName)

                    // 添加 key 确保项目正确识别
                    key(formulaName) {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp)
                                .clickable {
                                    if (selectedFormulas.isNotEmpty()) {
                                        // 在批量选择模式下，点击切换选择状态
                                        selectedFormulas = if (isSelected) {
                                            selectedFormulas - formulaName
                                        } else {
                                            // 选择项目时震动
                                            VibrationUtils.vibrate(context, 30)
                                            selectedFormulas + formulaName
                                        }
                                    }
                                }
                                .pointerInput(Unit) {
                                    detectTapGestures(
                                        onTap = {
                                            if (selectedFormulas.isEmpty()) {
                                                onFormulaClick(formulaName)
                                            }
                                        },
                                        onLongPress = {
                                            // 长按进入批量选择模式
                                            VibrationUtils.vibrate(context, 30)
                                            selectedFormulas = selectedFormulas + formulaName
                                        }
                                    )
                                },
                            colors = CardDefaults.cardColors(
                                containerColor = if (isSelected)
                                    MaterialTheme.colorScheme.primaryContainer
                                else
                                    MaterialTheme.colorScheme.surfaceVariant
                            )
                        )  {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                // 添加选择指示器
                                if (selectedFormulas.isNotEmpty()) {
                                    Checkbox(
                                        checked = isSelected,
                                        onCheckedChange = { checked ->
                                            selectedFormulas = if (checked) {
                                                selectedFormulas + formulaName
                                            } else {
                                                selectedFormulas - formulaName
                                            }
                                        },
                                        modifier = Modifier.padding(end = 8.dp)
                                    )
                                } else {
                                    // 原来的序号显示
                                    Box(
                                        modifier = Modifier
                                            .size(24.dp)
                                            .background(
                                                color = MaterialTheme.colorScheme.primary,
                                                shape = CircleShape
                                            ),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Text(
                                            text = "${filteredFormulas.indexOf(Pair(formulaName, lastModified)) + 1}",
                                            style = MaterialTheme.typography.bodySmall.copy(
                                                color = MaterialTheme.colorScheme.onPrimary
                                            )
                                        )
                                    }
                                    Spacer(modifier = Modifier.width(16.dp))
                                }

                                // 公式信息
                                Column(modifier = Modifier.weight(1f)) {
                                    // 公式名称
                                    if (searchQuery.isNotEmpty() && formulaName.contains(searchQuery, ignoreCase = true)) {
                                        val startIndex = formulaName.indexOf(searchQuery, ignoreCase = true)
                                        val endIndex = startIndex + searchQuery.length
                                        Text(
                                            text = buildAnnotatedString {
                                                append(formulaName.substring(0, startIndex))
                                                withStyle(
                                                    style = SpanStyle(
                                                        background = MaterialTheme.colorScheme.primary.copy(alpha = 0.3f),
                                                        fontWeight = FontWeight.Bold
                                                    )
                                                ) {
                                                    append(formulaName.substring(startIndex, endIndex))
                                                }
                                                append(formulaName.substring(endIndex))
                                            },
                                            style = MaterialTheme.typography.bodyLarge.copy(
                                                fontWeight = FontWeight.Bold
                                            )
                                        )
                                    } else {
                                        Text(
                                            text = formulaName,
                                            style = MaterialTheme.typography.bodyLarge.copy(
                                                fontWeight = FontWeight.Bold
                                            )
                                        )
                                    }

                                    // 创建日期
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        modifier = Modifier.padding(top = 4.dp)
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Edit,
                                            contentDescription = "创建时间",
                                            modifier = Modifier.size(14.dp),
                                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                        Spacer(modifier = Modifier.width(4.dp))
                                        Text(
                                            text = "创建于: ${dateFormat.format(Date(lastModified))}",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }

                                // 修改删除按钮，在批量选择模式下隐藏
                                if (selectedFormulas.isEmpty()) {
                                    IconButton(
                                        onClick = {
                                            // 点击时立即震动
                                            VibrationUtils.vibrate(context)
                                            deletingFormula = formulaName
                                            showDeleteDialog = true
                                        },
                                        modifier = Modifier
                                            .size(48.dp)
                                            .border(
                                                width = 1.dp,
                                                color = MaterialTheme.colorScheme.error,
                                                shape = CircleShape
                                            )
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Delete,
                                            contentDescription = "删除公式",
                                            tint = MaterialTheme.colorScheme.error,
                                            modifier = Modifier.size(24.dp)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }

                // 列表底部添加间距
                item {
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        }
    }


    // 删除确认对话框
    if (showDeleteDialog && deletingFormula != null) {
        AlertDialog(
            onDismissRequest = {
                showDeleteDialog = false
                deletingFormula = null
            },
            title = { Text("删除公式") },
            text = { Text("确定要删除公式 ${deletingFormula} 吗？此操作不可恢复。") },
            confirmButton = {
                Button(
                    onClick = {
                        // 添加震动效果
                        VibrationUtils.vibrate(context)

                        if (deleteFormula(context, deletingFormula!!)) {
                            formulas.removeIf { it.first == deletingFormula }
                            Toast.makeText(context, "公式已删除", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show()
                        }
                        showDeleteDialog = false
                        deletingFormula = null
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error,
                        contentColor = MaterialTheme.colorScheme.onError
                    )
                ) {
                    Text("删除")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showDeleteDialog = false
                        deletingFormula = null
                    }
                ) {
                    Text("取消")
                }
            }
        )
    }

    // 批量删除对话框
    if (showBulkDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showBulkDeleteDialog = false },
            title = { Text("批量删除") },
            text = { Text("确定要删除选中的 ${selectedFormulas.size} 个公式吗？此操作不可恢复。") },
            confirmButton = {
                Button(
                    onClick = {
                        selectedFormulas.forEach { formulaName ->
                            if (deleteFormula(context, formulaName)) {
                                formulas.removeIf { it.first == formulaName }
                            }
                        }
                        Toast.makeText(
                            context,
                            "已删除 ${selectedFormulas.size} 个公式",
                            Toast.LENGTH_SHORT
                        ).show()
                        selectedFormulas = emptySet()
                        showBulkDeleteDialog = false
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error,
                        contentColor = MaterialTheme.colorScheme.onError
                    )
                ) {
                    Text("删除")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showBulkDeleteDialog = false }
                ) {
                    Text("取消")
                }
            }
        )
    }

}




@Composable
fun OperatorButtons(
    onOperatorClick: (String) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true
) {
    Column(modifier = modifier) {
        Text(
            text = "运算符:",
            style = MaterialTheme.typography.bodyMedium,
            color = if (enabled) MaterialTheme.colorScheme.onSurface
            else MaterialTheme.colorScheme.onSurfaceVariant
        )
        Spacer(modifier = Modifier.height(8.dp))
        Row {
            listOf("+", "-", "*", "/").forEach { op ->
                Button(
                    onClick = { onOperatorClick(op) },
                    modifier = Modifier
                        .padding(horizontal = 4.dp)
                        .height(46.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = Color.White,
                        disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                        disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant
                    ),
                    elevation = ButtonDefaults.buttonElevation(
                        defaultElevation = 4.dp,
                        pressedElevation = 8.dp
                    ),
                    enabled = enabled
                ) {
                    Text(op, style = MaterialTheme.typography.bodyLarge)
                }
            }
        }
        Spacer(modifier = Modifier.height(8.dp))
        Row {
            listOf("(", ")", "=", "^").forEach { op ->
                Button(
                    onClick = { onOperatorClick(op) },
                    modifier = Modifier
                        .padding(horizontal = 4.dp)
                        .height(46.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = Color.White,
                        disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                        disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant
                    ),
                    elevation = ButtonDefaults.buttonElevation(
                        defaultElevation = 4.dp,
                        pressedElevation = 8.dp
                    ),
                    enabled = enabled
                ) {
                    Text(op, style = MaterialTheme.typography.bodyLarge)
                }
            }
        }
    }
}


@Composable
fun FunctionButtons(
    onFunctionClick: (String) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true
) {
    Column(modifier = modifier) {
        Text(
            text = "常用函数:",
            style = MaterialTheme.typography.bodyMedium,
            color = if (enabled) MaterialTheme.colorScheme.onSurface
            else MaterialTheme.colorScheme.onSurfaceVariant
        )
        Spacer(modifier = Modifier.height(8.dp))
        FlowRow(
            modifier = Modifier.fillMaxWidth(),
            mainAxisSpacing = 8.dp,
            crossAxisSpacing = 8.dp
        ) {
            listOf("sqrt", "pow", "sin", "cos", "tan", "log").forEach { func ->
                Button(
                    onClick = {
                        onFunctionClick("$func()") // 自动添加括号
                    },
                    modifier = Modifier
                        .padding(vertical = 4.dp)
                        .height(46.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.secondary,
                        contentColor = Color.White,
                        disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                        disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant
                    ),
                    elevation = ButtonDefaults.buttonElevation(
                        defaultElevation = 4.dp,
                        pressedElevation = 8.dp
                    ),
                    enabled = enabled
                ) {
                    Text("$func()", style = MaterialTheme.typography.bodyMedium)
                }
            }
        }
    }
}

@Composable
fun VariableQuickInsert(
    variables: List<Pair<String, String>>,
    onVariableClick: (String) -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true
) {
    if (variables.isNotEmpty()) {
        Column(modifier = modifier) {
            Text(
                text = "变量快捷插入:",
                style = MaterialTheme.typography.bodyMedium,
                color = if (enabled) MaterialTheme.colorScheme.onSurface
                else MaterialTheme.colorScheme.onSurfaceVariant
            )
            Spacer(modifier = Modifier.height(8.dp))
            FlowRow(
                modifier = Modifier.fillMaxWidth(),
                mainAxisSpacing = 8.dp,
                crossAxisSpacing = 8.dp
            ) {
                variables.forEach { (name, _) ->
                    Button(
                        onClick = { onVariableClick(name) },
                        modifier = Modifier
                            .padding(vertical = 4.dp)
                            .height(46.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.tertiary,
                            contentColor = Color.White
                        ),
                        elevation = ButtonDefaults.buttonElevation(
                            defaultElevation = 4.dp,
                            pressedElevation = 8.dp
                        ),
                        enabled = enabled
                    ) {
                        Text(name, style = MaterialTheme.typography.bodyMedium)
                    }
                }
            }
        }
    }
}


/**
 * 公式编辑器界面组件
 * 提供公式的创建和编辑功能，支持以下特性：
 * - 公式名称和变量定义
 * - 公式表达式构建
 * - 运算符和函数快捷输入
 * - 公式验证和测试
 * - 保存公式到本地存储
 *
 * @param onBackClick 返回按钮点击回调函数
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FormulaEditorScreen(onBackClick: () -> Unit) {
    val context = LocalContext.current
    rememberCoroutineScope()
    var formulaName by remember { mutableStateOf(TextFieldValue()) }
    var isConfirmed by remember { mutableStateOf(false) } // 添加这行
    var isFormulaTested by remember { mutableStateOf(false) }
    var variableUsageCount by remember { mutableStateOf(mapOf<String, Int>()) }

    fun deleteLastComponent(formula: TextFieldValue): TextFieldValue {
        val text = formula.text
        if (text.isEmpty()) return formula

        // 1. 优先匹配变量名（由字母、数字和下划线组成）
        val varPattern = Regex("([a-zA-Z_][a-zA-Z0-9_]*)\\s*$")
        val varMatch = varPattern.find(text)

        // 2. 匹配运算符（包括多字符运算符）
        val opPattern = Regex("([+\\-*/^=()])\\s*$")
        val opMatch = opPattern.find(text)

        return when {
            varMatch != null -> {
                val varName = varMatch.groupValues[1]
                TextFieldValue(
                    text = text.dropLast(varName.length),
                    selection = TextRange(text.length - varName.length)
                )
            }
            opMatch != null -> {
                val op = opMatch.groupValues[1]
                TextFieldValue(
                    text = text.dropLast(op.length),
                    selection = TextRange(text.length - op.length)
                )
            }
            else -> {
                // 默认删除最后一个字符
                TextFieldValue(
                    text = text.dropLast(1),
                    selection = TextRange(text.length - 1)
                )
            }
        }
    }
    var formulaContent by remember { mutableStateOf(TextFieldValue()) }
    var variables by remember { mutableStateOf(listOf<Pair<String, String>>()) }
    var currentVarName by remember { mutableStateOf(TextFieldValue()) }
    var testResult by remember { mutableStateOf<Double?>(null) }
    var targetVariable by remember { mutableStateOf("") }
    var isEditable by remember { mutableStateOf(false) }

    // Track variable usage in formula and reset test status
    LaunchedEffect(formulaContent.text) {
        isFormulaTested = false
        variableUsageCount = countVariableUsage(formulaContent.text, variables)
    }

    // Clear formula content when variables list becomes empty
    LaunchedEffect(variables.isEmpty()) {
        if (variables.isEmpty()) {
            formulaContent = TextFieldValue("")
        }
    }

    // 当目标变量变化时，更新变量值
    LaunchedEffect(targetVariable) {
        variables = variables.map { (name, value) ->
            if (name == targetVariable) {
                name to "?" // 目标变量设为"?"
            } else {
                // 其他变量如果为空则设为"1"
                name to if (value.isBlank() || value == "?") "1" else value
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState())
    ) {
        // 返回按钮
        Button(
            onClick = onBackClick,
            modifier = Modifier.padding(bottom = 16.dp)
        ) {
            Text("返回主菜单")
        }

        // 公式使用说明卡片
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            elevation = CardDefaults.cardElevation(4.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            )
        ) {
            Column(modifier = Modifier.padding(12.dp)) {
                Text(
                    text = "公式编辑说明",
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.primary
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "1. 先给公式取个名，再定义变量名",
                    style = MaterialTheme.typography.bodySmall
                )
                Text(
                    text = "2. 然后构建公式表达式",
                    style = MaterialTheme.typography.bodySmall
                )
                Text(
                    text = "3. 最后测试并保存公式",
                    style = MaterialTheme.typography.bodySmall
                )
                Text(
                    text = "示例: 伤害 = (攻击力 + 武器加成) * 暴击倍率",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }

        // 公式名称输入框
        TextField(
            value = formulaName,
            onValueChange = { formulaName = it },
            label = { Text("在此输入公式名称") },
            modifier = Modifier.fillMaxWidth()
        )

        Spacer(modifier = Modifier.height(8.dp))

        Column(modifier = Modifier.fillMaxWidth()) {
            Text(
                text = "变量定义",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(bottom = 4.dp)
            )

            // Variable input row with improved styling
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(2.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f)
                )
            ) {
                Column(modifier = Modifier.padding(12.dp)) {
                    // Variable name input with improved styling
                    OutlinedTextField(
                        value = currentVarName,
                        onValueChange = {
                            if (!isConfirmed) {
                                if (it.text.matches(Regex("^[\\p{L}_][\\p{L}0-9_]*$")) || it.text.isEmpty()) {
                                    currentVarName = it
                                }
                            }
                        },
                        label = {
                            Text(
                                "变量名",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        },
                        enabled = !isConfirmed,
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        colors = TextFieldDefaults.outlinedTextFieldColors(
                            focusedBorderColor = MaterialTheme.colorScheme.primary,
                            unfocusedBorderColor = MaterialTheme.colorScheme.outline,
                            disabledBorderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
                            disabledTextColor = MaterialTheme.colorScheme.onSurface,
                            disabledLabelColor = MaterialTheme.colorScheme.onSurfaceVariant
                        ),
                        shape = RoundedCornerShape(8.dp),
                        trailingIcon = {
                            if (currentVarName.text.isNotBlank()) {
                                IconButton(
                                    onClick = { currentVarName = TextFieldValue() },
                                    modifier = Modifier.size(24.dp)
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Close,
                                        contentDescription = "清除",
                                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    )

                    // Help text with improved styling
                    Text(
                        text = "可以包含中文、字母、数字和下划线，但不能是纯数字",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.outline,
                        modifier = Modifier.padding(top = 4.dp, start = 4.dp)
                    )

                    // Default value display with improved styling
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "默认值:",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(end = 8.dp)
                        )
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .height(TextFieldDefaults.MinHeight)
                                .background(
                                    color = MaterialTheme.colorScheme.surfaceVariant,
                                    shape = RoundedCornerShape(8.dp)
                                )
                                .border(
                                    width = 1.dp,
                                    color = MaterialTheme.colorScheme.outline,
                                    shape = RoundedCornerShape(8.dp)
                                )
                                .padding(horizontal = 16.dp),
                            contentAlignment = Alignment.CenterStart
                        ) {
                            Text(
                                text = "1",
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }

                    // Add button with improved styling
                    Button(
                        onClick = {
                            if (!isConfirmed && currentVarName.text.isNotBlank()) {
                                if (!isValidVariableName(currentVarName.text)) {
                                    Toast.makeText(
                                        context,
                                        "变量名可以包含中文、字母、数字和下划线，但不能是纯数字",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                    return@Button
                                }
                                variables = variables + (currentVarName.text to "1")
                                Toast.makeText(
                                    context,
                                    "变量 ${currentVarName.text} 已添加成功",
                                    Toast.LENGTH_SHORT
                                ).show()
                                currentVarName = TextFieldValue()
                            }
                        },
                        enabled = !isConfirmed && currentVarName.text.isNotBlank(), // Disabled when empty
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 12.dp),
                        shape = RoundedCornerShape(8.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary,
                            disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                            disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant
                        ),
                        elevation = ButtonDefaults.buttonElevation(
                            defaultElevation = 2.dp,
                            pressedElevation = 4.dp
                        )
                    ) {
                        Text(
                            "添加变量",
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier.padding(vertical = 4.dp)
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 已添加变量列表（修改部分）
            if (variables.isNotEmpty()) {
                Column {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text("已添加变量 (${variables.size}个):",
                            style = MaterialTheme.typography.bodySmall,
                            modifier = Modifier.weight(1f))

                        // 清空按钮 - 仅在未确认时显示
                        if (!isConfirmed) {
                            TextButton(
                                onClick = {
                                    variables = emptyList()
                                    formulaContent = TextFieldValue("")
                                    targetVariable = ""
                                    testResult = null
                                },
                                modifier = Modifier.padding(start = 8.dp)
                            ) {
                                Text("清空全部", color = MaterialTheme.colorScheme.error)
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(4.dp))
                    Column(modifier = Modifier.padding(start = 8.dp)) {
                        variables.forEachIndexed { index, (name, value) ->
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier.padding(vertical = 2.dp)
                            ) {
                                Text(
                                    text = "$name (使用次数: ${variableUsageCount[name] ?: 0})",
                                    modifier = Modifier.weight(1f)
                                )
                                // 删除按钮 - 仅在未确认时显示
                                if (!isConfirmed) {
                                    IconButton(
                                        onClick = {
                                            // Remove this variable
                                            variables = variables.toMutableList().apply {
                                                removeAt(index)
                                            }
                                            // Also remove from formula if used
                                            if (formulaContent.text.contains(name)) {
                                                formulaContent = TextFieldValue(
                                                    formulaContent.text.replace(name, "")
                                                )
                                            }
                                            // Reset target if it was this variable
                                            if (targetVariable == name) {
                                                targetVariable = ""
                                            }
                                        },
                                        modifier = Modifier.size(20.dp)
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Delete,
                                            contentDescription = "删除变量",
                                            tint = MaterialTheme.colorScheme.error,
                                            modifier = Modifier.size(16.dp)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // Formula building section - modified to be disabled when no variables
        Column {
            Text(
                text = "公式构建",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(bottom = 4.dp),
                color = if (variables.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant
                else MaterialTheme.colorScheme.onSurface
            )

            // Formula input field
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                OutlinedTextField(
                    value = formulaContent,
                    onValueChange = { newValue ->
                        if (!isConfirmed && variables.isNotEmpty()) {
                            // Always allow cursor movement and deletion
                            if (newValue.text.length < formulaContent.text.length) {
                                formulaContent = newValue
                            }
                            // Allow only numbers, decimal point, and existing variables/operators
                            else {
                                val currentText = formulaContent.text
                                val newText = newValue.text

                                // Check if the change is at the cursor position
                                val cursorPos = newValue.selection.start
                                val addedText = if (cursorPos > 0 && cursorPos <= newText.length) {
                                    newText.substring(cursorPos - 1, cursorPos)
                                } else ""

                                // Allow if:
                                // 1. It's a number or decimal point
                                // 2. It's an operator that was inserted via buttons
                                if (addedText.matches(Regex("[0-9.]")) ||
                                    newText.contains(Regex("[+\\-*/^=()]"))) {
                                    formulaContent = newValue
                                }
                            }
                        }
                    },
                    label = { Text("等式公式") },
                    modifier = Modifier.weight(1f),
                    readOnly = isConfirmed || variables.isEmpty(),
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f),
                        unfocusedBorderColor = MaterialTheme.colorScheme.outline,
                        disabledTextColor = MaterialTheme.colorScheme.onSurfaceVariant,
                        disabledLabelColor = MaterialTheme.colorScheme.onSurfaceVariant,
                        disabledBorderColor = MaterialTheme.colorScheme.outline
                    ),
                    placeholder = {
                        Text(
                            text = if (variables.isEmpty()) "请先添加变量"
                            else "可通过键盘输入数字或使用下方按钮构建公式",
                            color = MaterialTheme.colorScheme.outline
                        )
                    }
                )

                // Backspace button - only shown when not confirmed and variables exist
                if (!isConfirmed && variables.isNotEmpty()) {
                    IconButton(
                        onClick = {
                            formulaContent = deleteLastComponent(formulaContent)
                        },
                        modifier = Modifier.padding(start = 8.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Backspace,
                            contentDescription = "退格",
                            tint = MaterialTheme.colorScheme.error
                        )
                    }

                    // Clear button
                    IconButton(
                        onClick = {
                            formulaContent = TextFieldValue("")
                            testResult = null
                        },
                        modifier = Modifier.padding(start = 4.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Delete,
                            contentDescription = "清除公式",
                            tint = MaterialTheme.colorScheme.error
                        )
                    }
                }
            }

            // Update the hint text to reflect the change:
            Text(
                text = if (variables.isEmpty()) "请先添加变量再构建公式"
                else "提示：可通过键盘输入数字或使用下方按钮构建公式",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline,
                modifier = Modifier.padding(top = 4.dp)
            )
        }

        // 确认/取消确认按钮
        Button(
            onClick = {
                if (isConfirmed) {
                    // 取消确认
                    isConfirmed = false
                } else {
                    try {
                        // 确认公式前检查条件
                        if (formulaContent.text.isBlank()) {
                            Toast.makeText(context, "请先构建公式", Toast.LENGTH_SHORT).show()
                            return@Button
                        }

                        // 检查是否是等式格式
                        if (!formulaContent.text.contains("=")) {
                            Toast.makeText(context, "公式必须是等式形式（包含=号）", Toast.LENGTH_SHORT).show()
                            return@Button
                        }

                        // 检查等式两边是否都有内容
                        val parts = formulaContent.text.split("=").map { it.trim() }
                        if (parts.size != 2 || parts[0].isEmpty() || parts[1].isEmpty()) {
                            Toast.makeText(context, "等式两边都必须有表达式", Toast.LENGTH_SHORT).show()
                            return@Button
                        }

                        // 检查变量是否定义
                        if (variables.isEmpty()) {
                            Toast.makeText(context, "请至少添加一个变量", Toast.LENGTH_SHORT).show()
                            return@Button
                        }

                        // 检查是否有被除数为0的情况
                        if (hasDivisionByZero(formulaContent.text)) {
                            Toast.makeText(context, "公式内部有被除数为0，无法确认公式", Toast.LENGTH_SHORT).show()
                            return@Button
                        }

                        // 验证公式有效性
                        if (!validateFormula(formulaContent.text, variables)) {
                            Toast.makeText(context, "公式无效，请检查变量和语法", Toast.LENGTH_SHORT).show()
                            return@Button
                        }

                        // 检查等号两边是否都包含变量
                        val varNames = variables.map { it.first }
                        val leftHasVar = varNames.any { parts[0].contains(it) }
                        val rightHasVar = varNames.any { parts[1].contains(it) }

                        if (!leftHasVar || !rightHasVar) {
                            Toast.makeText(context, "等式两边都必须包含至少一个变量", Toast.LENGTH_SHORT).show()
                            return@Button
                        }

                        isConfirmed = true
                    } catch (e: IllegalArgumentException) {
                        Toast.makeText(context, "公式错误: ${e.message}", Toast.LENGTH_SHORT).show()
                    } catch (e: Exception) {
                        Toast.makeText(context, "公式无效，请检查变量和语法", Toast.LENGTH_SHORT).show()
                    }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = if (isConfirmed) MaterialTheme.colorScheme.error
                else MaterialTheme.colorScheme.primary
            ),
            enabled = variables.isNotEmpty()
        ) {
            Text(if (isConfirmed) "取消确认" else "确认公式")
        }

        // 显示确认后的公式 - 只保留这一个
        if (isConfirmed) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    contentColor = MaterialTheme.colorScheme.onPrimaryContainer
                ),
                elevation = CardDefaults.cardElevation(8.dp)
            ) {
                Text(
                    text = "已确认公式: ${formulaContent.text}",
                    modifier = Modifier.padding(16.dp),
                    style = MaterialTheme.typography.bodyLarge.copy(
                        fontWeight = FontWeight.Bold
                    )
                )
            }
        }

        Spacer(modifier = Modifier.height(8.dp))

        // After the formula confirmation button, add this:
        AnimatedVisibility(
            visible = !isConfirmed && variables.isNotEmpty(), // Only show when not confirmed AND variables exist
            enter = fadeIn() + expandVertically(),
            exit = fadeOut() + shrinkVertically()
        ) {
            Column {
                Spacer(modifier = Modifier.height(8.dp))

                // Variable quick insert - now only shown when variables exist
                VariableQuickInsert(
                    variables = variables,
                    onVariableClick = { varName ->
                        formulaContent = if (isEditable) {
                            val currentPos = formulaContent.selection.start
                            val newText = formulaContent.text.substring(0, currentPos) +
                                    varName +
                                    formulaContent.text.substring(currentPos)
                            TextFieldValue(
                                text = newText,
                                selection = TextRange(currentPos + varName.length)
                            )
                        } else {
                            TextFieldValue(
                                text = formulaContent.text + varName,
                                selection = TextRange(formulaContent.text.length + varName.length)
                            )
                        }
                        // Update usage count
                        variableUsageCount = variableUsageCount.toMutableMap().apply {
                            put(varName, (this[varName] ?: 0) + 1)
                        }
                    },
                    modifier = Modifier.fillMaxWidth()
                )

                Spacer(modifier = Modifier.height(8.dp))

                // Operator buttons
                OperatorButtons(
                    onOperatorClick = { op ->
                        formulaContent = if (isEditable) {
                            val currentPos = formulaContent.selection.start
                            val newText = formulaContent.text.substring(0, currentPos) +
                                    op +
                                    formulaContent.text.substring(currentPos)
                            TextFieldValue(
                                text = newText,
                                selection = TextRange(currentPos + op.length)
                            )
                        } else {
                            TextFieldValue(
                                text = formulaContent.text + op,
                                selection = TextRange(formulaContent.text.length + op.length)
                            )
                        }
                    },
                    modifier = Modifier.fillMaxWidth()
                )

                Spacer(modifier = Modifier.height(8.dp))

                // Function buttons
                FunctionButtons(
                    onFunctionClick = { func ->
                        formulaContent = if (isEditable) {
                            val currentPos = formulaContent.selection.start
                            val newText = formulaContent.text.substring(0, currentPos) +
                                    func +
                                    formulaContent.text.substring(currentPos)
                            TextFieldValue(
                                text = newText,
                                selection = TextRange(currentPos + func.length)
                            )
                        } else {
                            TextFieldValue(
                                text = formulaContent.text + func,
                                selection = TextRange(formulaContent.text.length + func.length)
                            )
                        }
                    },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }

        // Show a warning card when no variables are defined - moved outside AnimatedVisibility
        if (variables.isEmpty()) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer,
                    contentColor = MaterialTheme.colorScheme.onErrorContainer
                )
            ) {
                Text(
                    text = "尚未定义任何变量，请先在上方添加变量",
                    modifier = Modifier.padding(16.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }

        Spacer(modifier = Modifier.height(8.dp))

        Spacer(modifier = Modifier.height(8.dp))

        // 测试计算区域
        Text("测试计算", style = MaterialTheme.typography.titleMedium)
        Spacer(modifier = Modifier.height(8.dp))

        // 只在公式确认后显示变量输入部分
        if (isConfirmed) {
            val variablesInFormula = variables.filter { (name, _) ->
                formulaContent.text.contains(name)
            }

            // 显示测试变量输入
            variablesInFormula.forEach { (name, defaultValue) ->
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(text = "$name = ", modifier = Modifier.width(100.dp))
                    if (name == targetVariable) {
                        // 如果是目标变量，显示"?"符号
                        Text(
                            text = "?",
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 8.dp),
                            style = MaterialTheme.typography.bodyLarge
                        )
                    } else {
                        var inputValue by remember { mutableStateOf(defaultValue) }

                        LaunchedEffect(targetVariable) {
                            // 当目标变量变化时，重置其他变量的值
                            if (name != targetVariable && inputValue == "?") {
                                inputValue = "1"
                            }
                        }

                        Column(modifier = Modifier.weight(1f)) {
                            TextField(
                                value = inputValue,
                                onValueChange = { newValue ->
                                    if (newValue.isEmpty() || newValue.matches(Regex("^-?\\d*\\.?\\d*$")) || newValue == "?") {
                                        // 确保只有一个变量可以是"?"
                                        if (newValue == "?" && variables.any { it.second == "?" && it.first != name }) {
                                            Toast.makeText(context, "只能有一个未知量", Toast.LENGTH_SHORT).show()
                                            return@TextField
                                        }
                                        inputValue = newValue
                                        variables = variables.map {
                                            if (it.first == name) it.first to newValue else it
                                        }
                                    }
                                },
                                placeholder = { Text("1") }
                            )
                            Text(
                                text = "输入数字或?表示未知量",
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.outline,
                                modifier = Modifier.padding(top = 4.dp, start = 16.dp)
                            )
                        }
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
            }

            // 添加目标变量选择 - also filter options to only variables in formula
            if (variablesInFormula.isNotEmpty()) {
                var expanded by remember { mutableStateOf(false) }
                val options = variablesInFormula.map { it.first }

                Column(modifier = Modifier.fillMaxWidth()) {
                    Text(
                        text = "选择求解变量:",
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(bottom = 4.dp)
                    )

                    Box(modifier = Modifier.fillMaxWidth()) {
                        ExposedDropdownMenuBox(
                            expanded = expanded,
                            onExpandedChange = { expanded = it }
                        ) {
                            TextField(
                                value = targetVariable,
                                onValueChange = {},
                                label = { Text("要求解的变量") },
                                trailingIcon = {
                                    ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
                                },
                                colors = ExposedDropdownMenuDefaults.textFieldColors(),
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .menuAnchor(),
                                readOnly = true
                            )
                        }

                        DropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            options.forEach { option ->
                                DropdownMenuItem(
                                    text = { Text(option) },
                                    onClick = {
                                        targetVariable = option
                                        expanded = false
                                        // 当选择新目标变量时，重置测试结果
                                        testResult = null
                                    }
                                )
                            }
                        }
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
            }
        } else {
            // 公式未确认时的提示
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Text(
                    text = "请先确认公式后再进行测试计算",
                    modifier = Modifier.padding(16.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }

        // 测试计算按钮


        // 1. Add this LaunchedEffect to clear test result when confirmation is canceled
        LaunchedEffect(isConfirmed) {
            if (!isConfirmed) {
                testResult = null
            }
        }

        // 2. Modify the test calculation button
        Button(
            onClick = {
                // Check if variables are defined
                if (variables.isEmpty()) {
                    Toast.makeText(context, "请先进行变量定义", Toast.LENGTH_SHORT).show()
                    return@Button
                }

                // Check if formula is built
                if (formulaContent.text.isBlank()) {
                    Toast.makeText(context, "请先构建公式", Toast.LENGTH_SHORT).show()
                    return@Button
                }

                // Check if formula is confirmed
                if (!isConfirmed) {
                    Toast.makeText(context, "请先确认公式后再测试求解", Toast.LENGTH_SHORT).show()
                    return@Button
                }

                // Check if target variable is selected
                if (targetVariable.isBlank()) {
                    Toast.makeText(context, "请选择要求解的变量", Toast.LENGTH_SHORT).show()
                    return@Button
                }

                try {
                    // 分割等式
                    val parts = formulaContent.text.split("=").map { it.trim() }
                    if (parts.size != 2) {
                        Toast.makeText(context, "无效的等式格式", Toast.LENGTH_SHORT).show()
                        return@Button
                    }

                    // 检查变量是否在两边
                    val (left, right) = parts
                    val varNames = variables.map { it.first }

                    // 检查是否只有一个未知量
                    val unknownCount = variables.count { it.second == "?" }
                    if (unknownCount > 1) {
                        Toast.makeText(context, "只能有一个未知量", Toast.LENGTH_SHORT).show()
                        return@Button
                    }

                    // 检查目标变量是否在等式中
                    if (!left.contains(targetVariable) && !right.contains(targetVariable)) {
                        // 如果目标变量不在等式中，尝试计算任意一边
                        try {
                            testResult = calculateExpression(left, variables.associate { it.first to it.second })
                            isFormulaTested = true
                            return@Button
                        } catch (e: Exception) {
                            try {
                                testResult = calculateExpression(right, variables.associate { it.first to it.second })
                                isFormulaTested = true
                                return@Button
                            } catch (e: Exception) {
                                Toast.makeText(context, "无法计算等式两边", Toast.LENGTH_SHORT).show()
                                return@Button
                            }
                        }
                    }

                    testResult = solveEquation(
                        equation = formulaContent.text,
                        target = targetVariable,
                        variables = variables.associate { it.first to it.second }
                    )

                    // After successful calculation
                    if (testResult != null) {
                        isFormulaTested = true
                    }
                } catch (e: Exception) {
                    Toast.makeText(context, "求解失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("测试求解")
        }

        // 3. Modify the test result display to only show when both confirmed AND has a result
        if (isConfirmed && testResult != null) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "计算结果:",
                        style = MaterialTheme.typography.titleSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    testResult?.let {
                        val formattedResult = if (abs(it) >= 1e6 || (abs(it) <= 1e-6 && it != 0.0)) {
                            "%.6e".format(it).replace(",", ".")
                        } else {
                            "%.6f".format(it).replace(Regex("\\.?0+$"), "")
                        }
                        Text(
                            text = "$targetVariable = $formattedResult",
                            style = MaterialTheme.typography.bodyLarge.copy(
                                fontWeight = FontWeight.Bold
                            )
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // Show warning if formula is confirmed but not tested
        if (!isFormulaTested && isConfirmed) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer,
                    contentColor = MaterialTheme.colorScheme.onErrorContainer
                )
            ) {
                Text(
                    text = "请先测试求解公式后再保存",
                    modifier = Modifier.padding(16.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }

        // 保存按钮
        Button(
            onClick = {
                if (!isFormulaTested) {
                    Toast.makeText(context, "请先测试求解正常后再保存", Toast.LENGTH_SHORT).show()
                    return@Button
                }
                if (formulaName.text.isBlank()) {
                    Toast.makeText(context, "请输入公式名称", Toast.LENGTH_SHORT).show()
                    return@Button
                }
                if (formulaContent.text.isBlank()) {
                    Toast.makeText(context, "请输入公式内容", Toast.LENGTH_SHORT).show()
                    return@Button
                }
                if (!validateFormula(formulaContent.text, variables)) {
                    Toast.makeText(context, "公式无效，请检查变量和语法", Toast.LENGTH_SHORT).show()
                    return@Button
                }
                saveFormula(
                    context = context,
                    name = formulaName.text,
                    content = formulaContent.text,
                    variables = variables,
                    target = targetVariable
                )
            },
            modifier = Modifier.fillMaxWidth(),
            enabled = isFormulaTested && formulaContent.text.isNotBlank(),
            colors = ButtonDefaults.buttonColors(
                containerColor = if (formulaName.text.isBlank()) MaterialTheme.colorScheme.errorContainer
                else MaterialTheme.colorScheme.primary,
                contentColor = if (formulaName.text.isBlank()) MaterialTheme.colorScheme.onErrorContainer
                else MaterialTheme.colorScheme.onPrimary,
                disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant
            )
        ) {
            Text(
                if (formulaName.text.isBlank()) "记得给公式命名再保存" else "保存公式"
            )
        }
    }
}

/**
 * 保存公式到文件
 * 将公式数据序列化并保存到应用的内部存储中
 *
 * @param context 应用上下文，用于访问文件系统
 * @param name 公式名称，作为文件名的一部分
 * @param formula 公式表达式字符串
 * @param variables 公式中的变量列表
 * @return 保存操作是否成功
 */
private fun saveFormula(
    context: android.content.Context,
    name: String,
    content: String,
    variables: List<Pair<String, String>>,
    target: String = ""
) {
    try {
        // 验证是否为等式
        if (!content.contains("=")) {
            Toast.makeText(context, "公式必须是等式形式（包含=号）", Toast.LENGTH_SHORT).show()
            return
        }

        if (name.isBlank()) {
            Toast.makeText(context, "公式名称不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        // 增强的公式数据结构
        val formulaData = buildString {
            append("[formula]\n")
            append("name=$name\n")
            append("expression=$content\n")  // 改为expression
            if (target.isNotBlank()) {
                append("target=$target\n")  // 保存目标变量
            }
            append("[variables]\n")
            variables.forEach { (varName, defaultValue) ->
                append("$varName=$defaultValue\n")
            }
        }

        // 确保文件名格式正确
        val fileName = "formula_${name.trim()}.txt"
        context.openFileOutput(fileName, Context.MODE_PRIVATE).use {
            it.write(formulaData.toByteArray())
            Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show()
        }
    } catch (e: Exception) {
        Toast.makeText(context, "保存失败: ${e.message}", Toast.LENGTH_SHORT).show()
    }
}

/**
 * 加载所有公式名称列表
 */
private fun loadFormulas(context: Context): List<String> {
    return context.fileList()
        ?.filter { it.startsWith("formula_") && it.endsWith(".txt") }
        ?.map { it.removePrefix("formula_").removeSuffix(".txt") }
        ?.filter { it.isNotBlank() } // 过滤掉空名称
        ?: emptyList()
}

private fun loadFormulasWithTimestamps(context: Context): List<Pair<String, Long>> {
    return context.fileList()
        ?.filter { it.startsWith("formula_") && it.endsWith(".txt") }
        ?.map { fileName ->
            val name = fileName.removePrefix("formula_").removeSuffix(".txt")
            val file = File(context.filesDir, fileName)
            name to file.lastModified()
        } ?: emptyList()
}

private fun loadAllFormulas(context: Context): List<FormulaData> {
    return context.fileList()
        ?.filter { it.startsWith("formula_") && it.endsWith(".txt") }
        ?.mapNotNull { fileName ->
            val name = fileName.removePrefix("formula_").removeSuffix(".txt")
            loadFormulaData(context, name)
        } ?: emptyList()
}

private fun saveImportedFormula(context: Context, formula: FormulaData) {
    try {
        val content = buildString {
            append("[formula]\n")
            append("name=${formula.name}\n")
            append("expression=${formula.expression}\n")
            if (formula.targetVariable.isNotBlank()) {
                append("target=${formula.targetVariable}\n")
            }
            append("[variables]\n")
            formula.variables.forEach { variable ->
                append("${variable.name}=${variable.defaultValue}\n")
            }
        }

        val fileName = "formula_${formula.name.trim()}.txt"
        context.openFileOutput(fileName, Context.MODE_PRIVATE).use {
            it.write(content.toByteArray())
        }
    } catch (e: Exception) {
        Log.e("Import", "保存导入公式失败: ${formula.name}", e)
    }
}



/**
 * 加载公式数据（增强版）
 */
private fun loadFormulaData(context: Context, name: String): FormulaData? {
    return try {
        val content = context.openFileInput("formula_$name.txt")
            .bufferedReader()
            .use { it.readText() }

        val lines = content.lines()
        val formulaSection = mutableListOf<String>()
        val variablesSection = mutableListOf<String>()
        var currentSection: MutableList<String>? = null

        lines.forEach { line ->
            when {
                line.startsWith("[formula]") -> {
                    currentSection = formulaSection
                    formulaSection.clear() // 清空以防重复
                }
                line.startsWith("[variables]") -> {
                    currentSection = variablesSection
                    variablesSection.clear() // 清空以防重复
                }
                currentSection != null && line.isNotBlank() -> {
                    currentSection?.add(line) // 安全添加
                }
            }
        }

        val nameLine = formulaSection.find { it.startsWith("name=") }
        val expressionLine = formulaSection.find { it.startsWith("expression=") }
        val targetLine = formulaSection.find { it.startsWith("target=") }

        if (nameLine != null && expressionLine != null) {
            FormulaData(
                name = nameLine.substringAfter("="),
                expression = expressionLine.substringAfter("="),
                variables = variablesSection.mapNotNull { line ->
                    line.split("=").takeIf { it.size >= 2 }?.let {
                        Variable(name = it[0], defaultValue = it[1])
                    }
                },
                targetVariable = targetLine?.substringAfter("=") ?: "" // 添加目标变量
            )
        } else {
            null
        }
    } catch (e: Exception) {
        null
    }
}

/**
 * 删除公式文件
 * @param context 上下文
 * @param name 公式名称
 */
private fun deleteFormula(context: Context, name: String): Boolean {
    return try {
        val fileName = "formula_${name.trim()}.txt"
        val file = File(context.filesDir, fileName)
        if (file.exists()) {
            file.delete()
            true
        } else {
            false
        }
    } catch (e: Exception) {
        false
    }
}

/**
 * 公式计算界面组件
 * 用于执行具体公式的计算，支持以下功能：
 * - 显示公式表达式
 * - 选择目标变量
 * - 输入已知变量值
 * - 执行计算并显示结果
 * - 自动格式化计算结果
 *
 * @param formulaName 要计算的公式名称
 * @param onBackClick 返回按钮点击回调函数
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FormulaCalculateScreen(
    formulaName: String,
    onBackClick: () -> Unit
) {
    val context = LocalContext.current
    val focusManager = LocalFocusManager.current
    var formulaData by remember { mutableStateOf<FormulaData?>(null) }
    var inputValues by remember { mutableStateOf(mapOf<String, String>()) }
    var targetVariable by remember { mutableStateOf("") }
    var result by remember { mutableStateOf<Double?>(null) }
    var showEquationHelp by remember { mutableStateOf(false) }
    var expanded by remember { mutableStateOf(false) }
    var showEmptyInputWarning by remember { mutableStateOf(false) } // 新增状态用于显示警告

    // 加载公式数据
    LaunchedEffect(formulaName) {
        formulaData = loadFormulaData(context, formulaName)
        // 初始化变量值，默认为空字符串而不是1
        inputValues = formulaData?.variables?.associate { it.name to "" } ?: emptyMap()
        // 默认选择第一个变量作为目标
        targetVariable = formulaData?.variables?.firstOrNull()?.name ?: ""
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState())
    ) {
        // 返回按钮
        Button(
            onClick = onBackClick,
            modifier = Modifier.padding(bottom = 16.dp)
        ) {
            Text("返回")
        }

        // 显示公式表达式
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            elevation = CardDefaults.cardElevation(4.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            )
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = "当前公式:",
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.primary
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = formulaData?.expression ?: "",
                    style = MaterialTheme.typography.bodyLarge
                )
            }
        }

        // 目标变量选择
        if (formulaData?.variables?.isNotEmpty() == true) {
            val options = formulaData?.variables?.map { it.name } ?: emptyList()

            Column(modifier = Modifier.fillMaxWidth()) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(
                        text = "求解目标:",
                        style = MaterialTheme.typography.bodyLarge,
                        modifier = Modifier.weight(1f)
                    )
                    IconButton(
                        onClick = { showEquationHelp = !showEquationHelp },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(Icons.Default.Visibility, "帮助")
                    }
                }

                if (showEquationHelp) {
                    Text(
                        text = "选择您想要求解的变量，其他变量请输入已知值",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                }

                Box(modifier = Modifier.fillMaxWidth()) {
                    ExposedDropdownMenuBox(
                        expanded = expanded,
                        onExpandedChange = { expanded = it }
                    ) {
                        TextField(
                            value = targetVariable,
                            onValueChange = {},
                            label = { Text("选择求解变量") },
                            trailingIcon = {
                                ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .menuAnchor(),
                            readOnly = true,
                            colors = ExposedDropdownMenuDefaults.textFieldColors()
                        )

                        ExposedDropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            options.forEach { option ->
                                DropdownMenuItem(
                                    text = { Text(option) },
                                    onClick = {
                                        targetVariable = option
                                        expanded = false
                                        // 当选择新目标变量时，重置测试结果
                                        result = null
                                    }
                                )
                            }
                        }
                    }
                }
            }
            Spacer(modifier = Modifier.height(16.dp))
        }

        // 计算按钮点击处理函数
        fun onCalculateClick() {
            // 检查是否有已知变量输入为空
            val hasEmptyInput = inputValues.any { (name, value) ->
                name != targetVariable && value.isBlank()
            }

            if (hasEmptyInput) {
                showEmptyInputWarning = true
                Toast.makeText(context, "已知量输入不完整，请填写所有已知变量", Toast.LENGTH_SHORT).show()
                return
            }

            showEmptyInputWarning = false
            focusManager.clearFocus()

            try {
                result = solveEquation(
                    equation = formulaData?.expression ?: "",
                    target = targetVariable,
                    variables = inputValues.mapValues { (_, value) ->
                        if (value.isBlank()) "1" else value // 这里理论上不会执行，因为前面已经检查过空值
                    }
                )
            } catch (e: Exception) {
                Toast.makeText(context, "计算失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }

        // 输入变量值部分修改为显示警告
        formulaData?.variables?.forEach { variable ->
            if (variable.name != targetVariable) {
                Column(modifier = Modifier.fillMaxWidth()) {
                    TextField(
                        value = inputValues[variable.name] ?: "",
                        onValueChange = { newValue ->
                            // 只允许数字、小数点和负号
                            if (newValue.isEmpty() || newValue.matches(Regex("^-?\\d*\\.?\\d*$"))) {
                                inputValues = inputValues + (variable.name to newValue)
                            }
                        },
                        label = { Text("${variable.name} (已知值)") },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 8.dp),
                        isError = showEmptyInputWarning && (inputValues[variable.name]?.isBlank() == true) // 显示错误状态
                    )
                    if (showEmptyInputWarning && (inputValues[variable.name]?.isBlank() == true)) {
                        Text(
                            text = "请输入已知值",
                            color = MaterialTheme.colorScheme.error,
                            style = MaterialTheme.typography.bodySmall,
                            modifier = Modifier.padding(start = 16.dp, top = 4.dp)
                        )
                    }
                }
            }
        }

        // 计算按钮
        Button(
            onClick = { onCalculateClick() },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp),
            enabled = targetVariable.isNotBlank()
        ) {
            Text("计算")
        }

        // 显示结果
        result?.let {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "计算结果:",
                        style = MaterialTheme.typography.titleSmall,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    val formattedResult = if (abs(it) >= 1e6 || (abs(it) <= 1e-6 && it != 0.0)) {
                        "%.6e".format(it).replace(",", ".")
                    } else {
                        "%.6f".format(it).replace(Regex("\\.?0+$"), "")
                    }
                    Text(
                        text = "$targetVariable = $formattedResult",
                        style = MaterialTheme.typography.headlineSmall
                    )
                }
            }
        }
    }
}


/**
 * 检查括号是否匹配
 */
private fun areParenthesesBalanced(expression: String): Boolean {
    var balance = 0
    for (char in expression) {
        when (char) {
            '(' -> balance++
            ')' -> balance--
        }
        if (balance < 0) return false // 闭括号出现在开括号前
    }
    return balance == 0
}

/**
 * 检查表达式是否有被除数为0的情况
 */
private fun hasDivisionByZero(expression: String): Boolean {
    // 检查形如 "/0" 或 "/ 0" 的情况
    return expression.contains(Regex("/\\s*0(\\D|$)"))
}

/**
 * 检查变量名是否有效
 */
private fun isValidVariableName(name: String): Boolean {
    // Allow Chinese characters, letters, numbers and underscores
    // But cannot be pure numbers
    return name.matches(Regex("^[\\p{L}_][\\p{L}0-9_]*$")) &&
            !name.matches(Regex("^[0-9]+$"))
}

/**
 * 验证公式表达式是否有效
 */
private fun validateFormula(expression: String, variables: List<Pair<String, String>>): Boolean {
    if (!expression.contains("=")) return false

    try {
        // 1. 检查是否有被除数为0的情况
        if (hasDivisionByZero(expression)) {
            throw IllegalArgumentException("公式中存在被除数为0的情况")
        }

        // 2. 验证变量名是否有效
        variables.forEach { (name, _) ->
            if (!isValidVariableName(name)) {
                throw IllegalArgumentException("无效的变量名: $name")
            }
        }

        val parts = expression.split("=").map { it.trim() }
        if (parts.size != 2 || parts[0].isEmpty() || parts[1].isEmpty()) {
            throw IllegalArgumentException("等式两边都必须有表达式")
        }

        val varNames = variables.map { it.first }.toTypedArray()

        // 2. 检查两边是否都包含变量
        val leftHasVar = varNames.any { parts[0].contains(it) }
        val rightHasVar = varNames.any { parts[1].contains(it) }

        if (!leftHasVar || !rightHasVar) {
            throw IllegalArgumentException("等式两边都必须包含至少一个变量")
        }

        // 3. 检查括号是否匹配
        if (!areParenthesesBalanced(expression)) {
            throw IllegalArgumentException("括号不匹配")
        }

        // 4. 检查相邻元素是否合规
        val invalidAdjacentPatterns = listOf(
            // 变量与变量相邻
            Regex("([\\p{L}_][\\p{L}0-9_]*)\\s+([\\p{L}_][\\p{L}0-9_]*)"),
            // 符号与符号相邻（允许部分运算符组合如 >=, <=, !=）
            Regex("([+\\-*/^=])\\s*([+\\-*/^=])"),
            // 变量与数字相邻
            Regex("([\\p{L}_][\\p{L}0-9_]*)\\s+([0-9]+)"),
            Regex("([0-9]+)\\s+([\\p{L}_][\\p{L}0-9_]*)"),
            // 变量与函数相邻（变量不在函数括号内）
            Regex("([\\p{L}_][\\p{L}0-9_]*)\\s+([a-zA-Z]+)\\("),
            // 函数与变量相邻（函数不在变量前）
            Regex("([a-zA-Z]+)\\([^)]*\\)\\s+([\\p{L}_][\\p{L}0-9_]*)"),
            // 数字与函数相邻（数字不在函数括号内）
            Regex("([0-9]+)\\s+([a-zA-Z]+)\\("),
            // 函数与数字相邻（函数不在数字前）
            Regex("([a-zA-Z]+)\\([^)]*\\)\\s+([0-9]+)")
        )

        parts.forEach { part ->
            invalidAdjacentPatterns.forEach { pattern ->
                if (pattern.containsMatchIn(part)) {
                    val match = pattern.find(part)!!
                    throw IllegalArgumentException("在'${match.value}'之间缺少运算符")
                }
            }
        }

        // 5. 验证两边表达式是否有效
        ExpressionBuilder(parts[0]).variables(*varNames).build()
        ExpressionBuilder(parts[1]).variables(*varNames).build()

        return true
    } catch (e: Exception) {
        return false
    }
}

/**
 * 解方程函数
 * @param equation 等式字符串，如 "a = b * c + d"
 * @param target 要求解的变量名
 * @param variables 已知变量值映射
 */
private fun solveEquation(equation: String, target: String, variables: Map<String, String>): Double {
    val parts = equation.split("=").map { it.trim() }
    if (parts.size != 2) throw IllegalArgumentException("无效的等式格式")

    val (left, right) = parts

    try {
        // 检查是否有被除数为0的情况
        if (hasDivisionByZero(left) || hasDivisionByZero(right)) {
            throw IllegalArgumentException("被除数为0，计算出错")
        }

        // 如果目标变量在左边，计算右边表达式
        if (left == target) {
            return calculateExpression(right, variables)
        }
        // 如果目标变量在右边，计算左边表达式
        else if (right == target) {
            return calculateExpression(left, variables)
        }

        // 处理简单加减法方程
        if (left.contains(target) && !right.contains(target)) {
            // 处理形如 a + b = c 的情况
            if (left.contains("+")) {
                val parts = left.split("+").map { it.trim() }
                if (parts[0] == target) {
                    return calculateExpression(right, variables) - calculateExpression(parts[1], variables)
                } else if (parts[1] == target) {
                    return calculateExpression(right, variables) - calculateExpression(parts[0], variables)
                }
            }
            // 处理形如 a - b = c 的情况
            else if (left.contains("-")) {
                val parts = left.split("-").map { it.trim() }
                if (parts[0] == target) {
                    return calculateExpression(right, variables) + calculateExpression(parts[1], variables)
                } else if (parts[1] == target) {
                    return calculateExpression(parts[0], variables) - calculateExpression(right, variables)
                }
            }
        }
        else if (right.contains(target) && !left.contains(target)) {
            // 处理形如 c = a + b 的情况
            if (right.contains("+")) {
                val parts = right.split("+").map { it.trim() }
                if (parts[0] == target) {
                    return calculateExpression(left, variables) - calculateExpression(parts[1], variables)
                } else if (parts[1] == target) {
                    return calculateExpression(left, variables) - calculateExpression(parts[0], variables)
                }
            }
            // 处理形如 c = a - b 的情况
            else if (right.contains("-")) {
                val parts = right.split("-").map { it.trim() }
                if (parts[0] == target) {
                    return calculateExpression(left, variables) + calculateExpression(parts[1], variables)
                } else if (parts[1] == target) {
                    return calculateExpression(parts[0], variables) - calculateExpression(left, variables)
                }
            }
        }

        // 如果目标变量在等式两边都存在
        if (left.contains(target) && right.contains(target)) {
            throw IllegalArgumentException("目标变量不能同时在等式两边出现")
        }

        // 如果以上简单情况都不匹配，使用数值方法求解
        return reorganizeAndCalculate(
            if (left.contains(target)) left else right,
            if (left.contains(target)) right else left,
            target,
            variables
        )
    } catch (e: Exception) {
        throw IllegalArgumentException("求解方程失败: ${e.message}")
    }
}

private fun reorganizeAndCalculate(expression: String, otherSide: String,
                                   target: String, variables: Map<String, String>): Double {
    try {
        // First try algebraic method for simple equations
        val otherValue = calculateExpression(otherSide, variables)

        // Handle simple linear equations like a + b = d
        return when {
            // Case: target + something = otherValue
            expression.startsWith("$target +") -> {
                val remaining = expression.substringAfter("$target +").trim()
                otherValue - calculateExpression(remaining, variables)
            }
            // Case: something + target = otherValue
            expression.endsWith("+ $target") -> {
                val remaining = expression.substringBefore("+ $target").trim()
                otherValue - calculateExpression(remaining, variables)
            }
            // Case: target - something = otherValue
            expression.startsWith("$target -") -> {
                val remaining = expression.substringAfter("$target -").trim()
                otherValue + calculateExpression(remaining, variables)
            }
            // Case: something - target = otherValue
            expression.endsWith("- $target") -> {
                val remaining = expression.substringBefore("- $target").trim()
                calculateExpression(remaining, variables) - otherValue
            }
            // Case: target * something = otherValue
            expression.startsWith("$target *") -> {
                val remaining = expression.substringAfter("$target *").trim()
                otherValue / calculateExpression(remaining, variables)
            }
            // Case: something * target = otherValue
            expression.endsWith("* $target") -> {
                val remaining = expression.substringBefore("* $target").trim()
                otherValue / calculateExpression(remaining, variables)
            }
            // Case: target / something = otherValue
            expression.startsWith("$target /") -> {
                val remaining = expression.substringAfter("$target /").trim()
                otherValue * calculateExpression(remaining, variables)
            }
            // Case: something / target = otherValue
            expression.endsWith("/ $target") -> {
                val remaining = expression.substringBefore("/ $target").trim()
                calculateExpression(remaining, variables) / otherValue
            }
            // If none of the simple patterns match, try numerical method
            else -> {
                // 尝试解析表达式结构
                val expr = ExpressionBuilder(expression)
                    .variables(*variables.keys.toTypedArray())
                    .build()

                // 设置变量值，将"?"替换为1（因为"?"表示未知量）
                variables.forEach { (name, value) ->
                    expr.setVariable(name, if (value == "?") 1.0 else value.toDoubleOrNull() ?: 1.0)
                }

                // 创建临时表达式来求解目标变量
                val tempExpr = ExpressionBuilder("$expression - $otherValue")
                    .variables(*variables.keys.toTypedArray())
                    .build()

                // 设置变量值
                variables.forEach { (name, value) ->
                    if (name != target) {
                        tempExpr.setVariable(name, if (value == "?") 1.0 else value.toDoubleOrNull() ?: 1.0)
                    }
                }

                // 使用数值方法求解方程
                var x = 1.0 // 初始猜测值
                var lastX = x
                var f: Double
                var iterations = 0
                val maxIterations = 100
                val tolerance = 1e-6

                do {
                    tempExpr.setVariable(target, x)
                    f = tempExpr.evaluate()

                    // 计算导数（数值微分）
                    val h = 1e-5
                    tempExpr.setVariable(target, x + h)
                    val fPlusH = tempExpr.evaluate()
                    val derivative = (fPlusH - f) / h

                    if (abs(derivative) < 1e-10) {
                        // 导数太小，可能收敛到局部最小值
                        throw IllegalArgumentException("无法求解方程，可能没有解或解不唯一")
                    }

                    lastX = x
                    x = x - f / derivative
                    iterations++
                } while (abs(f) > tolerance && iterations < maxIterations)

                if (iterations >= maxIterations) {
                    throw IllegalArgumentException("求解方程未收敛")
                }

                x
            }
        }
    } catch (e: Exception) {
        throw IllegalArgumentException("求解方程失败: ${e.message}")
    }
}

/**
 * 计算变量在公式中的使用次数
 */
private fun countVariableUsage(formula: String, variables: List<Pair<String, String>>): Map<String, Int> {
    return variables.associate { (name, _) ->
        name to formula.split(name).size - 1
    }
}

/**
 * 计算表达式
 */
private fun calculateExpression(expression: String, variables: Map<String, String>): Double {
    try {
        // 处理空表达式
        if (expression.isBlank()) return 0.0

        // 处理纯数字
        expression.toDoubleOrNull()?.let { return it }

        // 检查是否有被除数为0的情况
        if (hasDivisionByZero(expression)) {
            throw IllegalArgumentException("被除数为0，计算出错")
        }

        // 创建表达式构建器
        val builder = ExpressionBuilder(expression)

        // 添加所有变量
        variables.keys.forEach { builder.variable(it) }

        // 构建表达式
        val expr = builder.build()

        // 设置变量值
        variables.forEach { (name, value) ->
            // 如果变量值是"?"，则使用1作为默认值
            val numValue = if (value == "?") 1.0 else {
                try {
                    value.toDouble()
                } catch (e: NumberFormatException) {
                    // 如果无法解析为数字，使用默认值1
                    1.0
                }
            }
            expr.setVariable(name, numValue)
        }

        return expr.evaluate()
    } catch (e: Exception) {
        throw IllegalArgumentException("计算错误: ${e.message?.take(200)}")
    }
}